package com.capa.ui.chat

import android.app.Application
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.room.Room
import com.capa.MyApp
import com.capa.R
import com.capa.basic.BaseViewModel
import com.capa.constants.Constants
import com.capa.database.ChatMessageDatabase
import com.capa.model.ChatMessage
import com.capa.model.DeepSeekMessage
import com.capa.model.DeepSeekRequest
import com.capa.net.DataService
import com.capa.utils.SPreference

class ChatViewModel(application: Application) : BaseViewModel(application) {

    val messages = MutableLiveData<List<ChatMessage>>()
    val inputMessage = MutableLiveData<String>()
	val latestReply = MutableLiveData<String>()
    
    private val messageList = mutableListOf<ChatMessage>()
    private var messageId = 0L

    private val deepSeekMessageList = MutableLiveData<MutableList<DeepSeekMessage>>(mutableListOf<DeepSeekMessage>().apply {
        add(DeepSeekMessage("system", getApplication<Application>().getString(R.string.deepseek_system_role)))
    })

    var isGettingAnswer = MutableLiveData<Boolean>()

    private val db = Room.databaseBuilder(
        getApplication(),
        ChatMessageDatabase::class.java,
        "chat_message_database"
    ).allowMainThreadQueries().build()

    init {
        // 获得数据库数据

        db.chatMessageDao.getAll().forEach { message ->
            messageList.add(message)
        }

        messages.value = ArrayList(messageList)

        messageId = messageList.size.toLong()
    }

    fun setInputMessage(message: String) {
        inputMessage.value = message
    }

    fun sendMessage() {
        if(isGettingAnswer.value == true){
            Toast.makeText(getApplication(), "回复中，请稍后", Toast.LENGTH_SHORT).show()
            return
        }

        isGettingAnswer.value = true

        inputMessage.value?.let { content ->
            Log.i(Constants.TAG, "sendMessage: $content")
            if (content.isNotBlank()) {
                addMessage(
                    ChatMessage(
                        id = messageId++,
                        content = content,
                        timestamp = System.currentTimeMillis(),
                        isFromMe = true
                    )
                )

                inputMessage.value = ""

                // 模拟自动回复
                launch({
                    try{
                        // 延迟1秒回复
                        kotlinx.coroutines.delay(3000)
                        addMessage(
                            ChatMessage(
                                id = messageId++,
                                content = "收到你的消息：$content",
                                timestamp = System.currentTimeMillis(),
                                isFromMe = false
                            )
                        )
                    }finally {
                        isGettingAnswer.value=false
                    }
                })
            }
        }
    }

    fun sendMessageToDeepSeek() {
        if(isGettingAnswer.value == true){
            Toast.makeText(getApplication(), "回复中，请稍后", Toast.LENGTH_SHORT).show()
            return
        }

        isGettingAnswer.value = true

        inputMessage.value?.let { content ->
            Log.i(Constants.TAG, "sendMessage: $content")
            if (content.isNotBlank()) {
                addMessage(
                    ChatMessage(
                        id = messageId++,
                        content = content,
                        timestamp = System.currentTimeMillis(),
                        isFromMe = true
                    )
                )

                inputMessage.value = ""

                deepSeekMessageList.value?.let {
                    launch({
                        it.add(DeepSeekMessage("user", content))
                        val deepSeekRequest = DeepSeekRequest(messages = it)
                        val res = DataService.requestDeepSeek(3, deepSeekRequest)

                        Log.i(Constants.TAG, it.toString())
                        Log.i(Constants.TAG, res.toString())

                        val replyContent = res.choices.firstOrNull()?.message?.content
                        if (!replyContent.isNullOrBlank()) {
                            addMessage(
                                ChatMessage(
                                    id = messageId++,
                                    content = replyContent,
                                    timestamp = System.currentTimeMillis(),
                                    isFromMe = false
                                )
                            )
							latestReply.value = replyContent!!
                            it.add(DeepSeekMessage("assistant", replyContent))
                        } else {
                            throw IllegalStateException("API返回空回复")
                        }
                        isGettingAnswer.value = false

                    }, onError = {
                        //打印报错信息
                        if (Constants.IS_Production) Log.i(Constants.TAG, "DeepSeek Error: ${it}", it)
                        Toast.makeText(MyApp.get(), "请求失败", Toast.LENGTH_SHORT).show()
                    })
                }
            }
        }
    }

    private fun addMessage(message: ChatMessage) {
        messageList.add(message)
        db.chatMessageDao.insert(message)
        messages.value = ArrayList(messageList)
    }

    fun clearMessage() {
        messageList.clear()
        db.chatMessageDao.deleteAll()
        messages.value = ArrayList(messageList)
    }
}